<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-05-06 11:23:18
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-06-24 19:19:33
 * @FilePath: \ken147258.topayClient\src\views\other\system\basic-setting.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container" v-loading="loading">
    <div class="search-container">
      <FormList :initForm="initSearchForm" v-model:formModel="searchForm"></FormList>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="handleTableBtnClick({}, 'add')"
          ><i-ep-plus />新增</el-button
        >
      </template>
      <comTable
        :data="tableDatasCom"
        :config="tableconfig"
        :tableHeader="tableHeader"
        @link-click="handleTableBtnClick"
      >
        <template #type_com="{ row, index }">
          <span v-if="row.type == 1" style="color: darkorchid">后台</span>
          <span v-else-if="row.type == 2" style="color: blue">商户</span>
          <span v-else-if="row.type == 3" style="color: green">码商</span>
          <span v-else style="color: gray">-</span>
        </template>
      </comTable>

      <pagination
        v-if="tableDatasObj.paging.total > 0"
        v-model:total="tableDatasObj.paging.total"
        v-model:page="tableDatasObj.paging.page"
        v-model:limit="tableDatasObj.paging.limit"
        @pagination="handleQuery"
      />
    </el-card>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <FormList
        v-if="initDialogForm.initKeys.length"
        v-model:formRef="formDialogId"
        v-model:formModel="formDialogModel"
        :initForm="initDialogForm"
      ></FormList>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleLeftClick">{{
            dialog.leftBtnText
          }}</el-button>
          <el-button @click="handleRightClick">{{ dialog.rightBtnText }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { FormInstance } from "element-plus";
import { list, add, edit, deleteByIds } from "@/api/other/black";
import FormList from "@/components/FormList/index.vue";
import comTable from "@/components/comTable/comTable.vue";
import { cloneDeep } from "lodash";
import { list as listByPayer } from "@/api/other/merchant";

const getFormatDate = inject("getFormatDate");

const options = {
  limit_type: [
    {
      label: "IP",
      value: "1",
    },
    {
      label: "cookie",
      value: "2",
    },
  ],
};

const searchForm = ref({});
const initSearchForm = ref({
  // 表单标签位置
  // labelPosition: "right",
  formAttrs: {
    // 是否内联
    inline: true,
  },
  rowAttrs: {
    // 行内表单数量
    columnsNum: 4,
  },
  // 初始化表单字段
  initKeys: [
    {
      // 类型
      type: "select",
      // 唯一标识
      key: "limit_type",
      // 表单属性
      formAttrs: {
        label: "类型",
      },
      // 控制属性
      controlAttrs: {
        placeholder: "请选择类型",
        // 是否可清空
        clearable: true,
      },
      // 选项
      options: options.limit_type,
    },
    {
      // 类型
      type: "input",
      // 唯一标识
      key: "content",
      // 表单属性
      formAttrs: {
        label: "ip/cookie",
      },
      // 控制属性
      controlAttrs: {
        // 提示文本
        placeholder: "请输入",
        // 是否可清空
        clearable: true,
      },
      // 控制事件
      controlOn: {},
    },
    // {
    //   // 类型
    //   type: "date-picker",
    //   // 唯一标识
    //   key: "start_time",
    //   // 表单属性
    //   formAttrs: {
    //     label: "开始时间",
    //   },
    //   // 控制属性
    //   controlAttrs: {
    //     // 提示文本
    //     placeholder: "请选择开始时间",
    //     type: "datetime",
    //     // 是否可清空
    //     clearable: true,
    //     style: {
    //       width: "100%",
    //     },
    //   },
    //   // 控制事件
    //   controlOn: {},
    // },
    // {
    //   // 类型
    //   type: "date-picker",
    //   // 唯一标识
    //   key: "end_time",
    //   // 表单属性
    //   formAttrs: {
    //     label: "结束时间",
    //   },
    //   // 控制属性
    //   controlAttrs: {
    //     // 提示文本
    //     placeholder: "请选择结束时间",
    //     type: "datetime",
    //     value: defaultTime,
    //     // 是否可清空
    //     clearable: true,
    //     style: {
    //       width: "100%",
    //     },
    //   },
    //   // 控制事件
    //   controlOn: {},
    // },
    {
      // 类型
      type: "buttons",
      // 按钮
      btns: [
        {
          // 文本
          text: "搜索",
          // 控制属性
          controlAttrs: {
            // 类型
            type: "primary",
            icon: "search",
          },
          // 控制事件
          controlOn: {
            // 点击
            click: (e: Event, formRef: FormInstance, data: Array<object>) => {
              formRef.validate((valid) => {
                if (valid) {
                  console.log("fields", data);
                  tableDatasObj.value.paging.page = 1;

                  let tempData = { ...data };
                  tableDatasObj.value.queryParams = tempData;

                  // if (data.start_time) {
                  //   tempData.start_time = data.start_time.getTime() / 1000;
                  // }
                  // if (data.end_time) {
                  //   tempData.end_time = data.end_time.getTime() / 1000;
                  // }

                  tableDatasObj.value.queryParams = tempData;

                  handleQuery(tableDatasObj.value.paging);
                }
              });
            },
          },
        },
        {
          // 文本
          text: "重置",
          // 控制属性
          controlAttrs: {
            icon: "refresh",
          },
          // 控制事件
          controlOn: {
            // 点击
            click: resetQuery,
          },
        },
      ],
    },
  ],
});

/** 重置查询 */
function resetQuery(e: Event, formRef: FormInstance, data: Array<object>) {
  // 重置表单
  formRef.resetFields();
  // 查询
  tableDatasObj.value.paging.page = 1;
  tableDatasObj.value.paging.limit = 20;
  tableDatasObj.value.queryParams = { ...searchForm.value };
  const params = {
    ...tableDatasObj.value.queryParams,
    ...data,
    ...tableDatasObj.value.paging,
  };

  handleQuery(params);
}

// 表*********************************************
const loading = ref(false);

const tableDatasObj = ref({
  list: [],
  paging: {
    limit: 20,
    page: 1,
    total: 122,
  },
});
const tableDatasCom = computed(() => {
  return tableDatasObj.value.list.map((item: any) => {
    return {
      ...item,
      limit_typeCom: options.limit_type.find(
        (tItem) => tItem.value === item.limit_type.toString()
      )?.label,
      limit_timeCom: item.limit_time === 0 ? "永久" : item.limit_time + " (分钟)",
      createtimeCom: getFormatDate(item.createtime),
    };
  });
});

const tableconfig = {
  // tableHeight: 480, //表格高度
  isSelection: false, //显示复选框
  isRowClick: false, //使用行点击
  isStripe: true, //隐藏斑马纹，与背景色不可同时用
  isShowSummary: false, //显示共计
  isIndex: true, //自定义序号
  isNeedPagination: true, //是否需要分页
};
const tableHeader = [
  { label: "ID", prop: "id", width: 150 },
  { label: "商户号", prop: "mer_id", width: 150 },
  { label: "商户名称", prop: "mer_name", minWidth: 200 },
  { label: "类型", prop: "limit_typeCom", width: 150 },
  { label: "ip/cookie", prop: "content", width: 200 },
  { label: "限制时间", prop: "limit_timeCom", width: 200 },
  { label: "创建时间", prop: "createtimeCom", width: 200 },
  {
    label: "操作",
    isSort: false,
    prop: "operation",
    width: 100,
    children: [
      {
        type: "button",
        btnText: "解除",
        title: "relieve",
      },
    ],
  },
];

/**
 * 查询
 */
function handleQuery(paging: { page: number; limit: number }) {
  loading.value = true;
  list({ ...tableDatasObj.value.paging, ...tableDatasObj.value.queryParams })
    .then((res) => {
      tableDatasObj.value.list = res.list;
      tableDatasObj.value.paging.total = res.total;
    })
    .finally(() => (loading.value = false));
}
// 完*********************************************

const initDialogForm = ref({
  // 表单标签位置
  formAttrs: {
    // 是否内联
    // inline: true,
    labelPosition: "top",
  },
  rowAttrs: {
    // 行内表单数量
    columnsNum: 1,
  },
  // 初始化表单字段
  initKeys: <any>[],
});

let initDialogFormBak = cloneDeep(initDialogForm.value);

// 处理表格按钮点击事件
function handleTableBtnClick(row: object, title: string) {
  // 显示对话框
  dialog.type = title;
  dialog.visible = true;
  dialog.singleData = tableDatasCom.value.find((item) => item.id === row.id);

  // 新增支付产品
  if (title === "add") {
    dialog.width = 400;
    dialog.title = "新增限制";
    dialog.leftBtnText = "确 定";
    dialog.rightBtnText = "取 消";

    initDialogForm.value.initKeys.push(
      ...[
        {
          // 类型
          type: "select-v2",
          // 唯一标识
          key: "mer_id",
          // 表单属性
          formAttrs: {
            label: "商户号",
          },
          // 控制属性
          controlAttrs: {
            // 提示文本
            placeholder: "请输入商户号",
            // 是否可清空
            clearable: true,
            filterable: true,
          },
          // 控制事件
          controlOn: {},
        },
        {
          // 类型
          type: "select",
          // 唯一标识
          key: "limit_type",
          // 表单属性
          formAttrs: {
            label: "限制类型",
          },
          // 控制属性
          controlAttrs: {
            // 提示文本
            placeholder: "请选择限制类型",
            // 是否可清空
            clearable: true,
          },
          // 控制事件
          controlOn: {},
          options: options.limit_type,
        },
        {
          // 类型
          type: "input",
          // 唯一标识
          key: "content",
          // 表单属性
          formAttrs: {
            label: "限制内容",
          },
          // 控制属性
          controlAttrs: {
            // 提示文本
            placeholder: "请输入限制内容",
            // 是否可清空
            clearable: true,
          },
          // 控制事件
          controlOn: {},
        },
        {
          // 类型
          type: "input-number",
          // 唯一标识
          key: "limit_time",
          // 表单属性
          formAttrs: {
            label: "限制时间",
          },
          // 控制属性
          controlAttrs: {
            // 提示文本
            placeholder: "请输入限制时间（具体分钟，0表示永久）",
            // 是否可清空
            clearable: true,
            min: 0,
          },
          // 控制事件
          controlOn: {},
        },
      ]
    );

    listByPayer({
      page: 1,
      limit: 99999,
    }).then((res) => {
      initDialogForm.value.initKeys[0].controlAttrs.options = res.list.map((item) => {
        return {
          label: item.mer_name,
          value: item.id,
        };
      });
    });
  } else if (title === "relieve") {
    // 删除
    dialog.visible = false;

    ElMessageBox.confirm("你确定要解除该吗?", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      title: "提示",
    }).then(() => {
      let params = {
        ids: [row].map((item) => item.id).join(","),
      };

      deleteByIds(params).then((res) => {
        if (tableDatasObj.value.list.length === 1) {
          if (tableDatasObj.value.paging.page > 1) {
            --tableDatasObj.value.paging.page;
          }
        }
        handleQuery();
      });
    });
  }
}

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
  leftBtnText: "",
  rightBtnText: "取 消",
  singleData: {},
});
const dialogBak = cloneDeep(dialog);

let formDialogId = ref<FormInstance>();

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;

  setTimeout(() => {
    formDialogId.value = {};
    initDialogForm.value.initKeys.splice(0);
    Object.keys(dialogBak).map((key) => {
      dialog[key] = dialogBak[key];
    });

    initDialogForm.value = cloneDeep(initDialogFormBak);
  }, 600);
}

let formDialogModel = ref({});
function handleLeftClick() {
  if (dialog.type === "add") {
    formDialogId.value.validate((valid, fields) => {
      if (valid) {
        let params = { ...formDialogModel.value };

        // params.pass_show = params.pass_show ? 1 : 2;
        // params.order_float_amount = params.order_float_amount ? 1 : 2;
        // params.pay_page_sub_name = params.pay_page_sub_name ? 1 : 2;
        // params.int_skm_amount = params.int_skm_amount ? 1 : 2;
        // params.skm_amount_range = params.skm_amount_range ? 1 : 2;
        params.handle_order_status = params.handle_order_status ? 1 : 2;
        params.status = params.status ? 1 : 2;

        add(params).then((res) => {
          ElMessage.success("添加黑名单成功");
          closeDialog();
          handleQuery();
        });
      } else {
        console.log("error submit!", fields);
      }
    });
  }
}

function handleRightClick() {
  // formDialogId.
  closeDialog();
}

onMounted(() => {
  tableDatasObj.value.queryParams = { ...searchForm.value };

  handleQuery(tableDatasObj.value.paging);
});
</script>

<style scoped></style>
